import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

/**
 * @Author: YLBG-YCY-1325
 * @Description:
 * @Date: 2017/3/20
 */
public class EmailTest {
    private static String receiveMailAccount = "1330154682@qq.com";
    private static String myEamilHost = "smtp.163.com";
    private static String myEmailAccount = "18329031970@163.com";
    private static String myEmailPassword = "1158629261ycy";

    public static void main(String[] args) throws IOException, MessagingException, GeneralSecurityException {
//        MailSSLSocketFactory sf = new MailSSLSocketFactory();
//        sf.setTrustAllHosts(true);
        Properties properties = new Properties();
//        properties.put("mail.smtp.ssl.SocketFactory",sf);
//        properties.setProperty("mail.smtp.ssl.enable","true");
        properties.setProperty("mail.transport.protocol", "smtp"); // 使用协议
        properties.setProperty("mail.smtp.port","25");
        properties.setProperty("mail.smtp.host", myEamilHost);
        properties.setProperty("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(properties);
        session.setDebug(true);
        MimeMessage mimeMessage = createMimeMessage(session, myEmailAccount, receiveMailAccount);
        Transport transport = session.getTransport();
        transport.connect(myEamilHost, myEmailAccount,myEmailPassword);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();
    }

    public static MimeMessage createMimeMessage(Session session, String sendMail,
                                                String receiveMail) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = new MimeMessage(session);
        InternetAddress[] internetAddresses = new InternetAddress[2];
        internetAddresses[0] = new InternetAddress(receiveMail, "UTF-8");
        internetAddresses[1] = new InternetAddress("1158629261@qq.com", "UTF-8");
        message.setRecipients(Message.RecipientType.TO, internetAddresses);
        message.setFrom(new InternetAddress(sendMail, "Lemontree.com", "UTF-8"));
        message.setSubject("欢迎注册", "UTF-8");
        message.setContent("德   玛西亚", "text/html;charset=UTF-8");
        message.setSentDate(new Date());
        return message;
    }
}
